/*++

Module Name:

driver.c

Abstract:

This file contains the driver entry points and callbacks.

Environment:

Kernel-mode Driver Framework

--*/

#include "precomp.h"
#include "driver.h"
#include "driver.tmh"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, dnsfilterDeviceAdd)
#pragma alloc_text (PAGE, dnsfilterEvtDriverContextCleanup)
#pragma alloc_text (PAGE, dnsfilterEvtDriverUnload)
#endif

NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT  DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++

Routine Description:
DriverEntry initializes the driver and is the first routine called by the
system after the driver is loaded. DriverEntry specifies the other entry
points in the function driver, such as EvtDevice and DriverUnload.

Parameters Description:

DriverObject - represents the instance of the function driver that is loaded
into memory. DriverEntry must initialize members of DriverObject before it
returns to the caller. DriverObject is allocated by the system before the
driver is loaded, and it is released by the system after the system unloads
the function driver from memory.

RegistryPath - represents the driver specific path in the Registry.
The function driver can use the path to store driver related data between
reboots. The path does not store hardware instance specific data.

Return Value:

STATUS_SUCCESS if successful,
STATUS_UNSUCCESSFUL otherwise.

--*/
{
    WDF_DRIVER_CONFIG       config;
    NTSTATUS                status;
    WDF_OBJECT_ATTRIBUTES   attributes;
    WDFDRIVER               hDriver;
    PWDFDEVICE_INIT         pInit = NULL;
    PDEVICE_OBJECT          pDeviceObject = NULL;
    NET_BUFFER_LIST_POOL_PARAMETERS nblPoolParams = { 0 };
    NET_BUFFER_POOL_PARAMETERS      nbPoolParams = { 0 };
    //
    // Initialize WPP Tracing
    //
    WPP_INIT_TRACING(DriverObject, RegistryPath);
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");
    //
    // Register a cleanup callback so that we can call WPP_CLEANUP when
    // the framework driver object is deleted during driver unload.
    //
    WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
    attributes.EvtCleanupCallback = dnsfilterEvtDriverContextCleanup;
    WDF_DRIVER_CONFIG_INIT(
        &config,
        WDF_NO_EVENT_CALLBACK // This is a non-pnp driver. dnsfilterDeviceAdd
        );
    //
    // Tell the framework that this is non-pnp driver so that it doesn't
    // set the default AddDevice routine.
    //
    config.DriverInitFlags |= WdfDriverInitNonPnpDriver;
    //
    // NonPnp driver must explicitly register an unload routine for
    // the driver to be unloaded.
    //
    config.EvtDriverUnload = dnsfilterEvtDriverUnload;
    //
    // Create a framework driver object to represent our driver.
    //
    status = WdfDriverCreate(DriverObject,
        RegistryPath,
        &attributes,
        &config,
        &hDriver
        );
    if (!NT_SUCCESS(status)) {
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! WdfDriverCreate failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    //
    //
    // In order to create a control device, we first need to allocate a
    // WDFDEVICE_INIT structure and set all properties.
    //
    pInit = WdfControlDeviceInitAllocate(
        hDriver,
        &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RW_RES_R
        );
    if (pInit == NULL) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! WdfControlDeviceInitAllocate failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    //
    // Call dnsfilterDeviceAdd to create a deviceobject to represent our
    // software device.
    //
    status = dnsfilterDeviceAdd(hDriver, pInit);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! dnsfilterDeviceAdd failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    pDeviceObject = WdfDeviceWdmGetDeviceObject(g_wdfControlDevice);
    g_pNdisGenericObj = NdisAllocateGenericObject(
        DriverObject,
        POOL_TAG,
        0
        );
    if (NULL == g_pNdisGenericObj)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! NdisAllocateGenericObject failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    nblPoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
    nblPoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
    nblPoolParams.Header.Size = NDIS_SIZEOF_NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
    nblPoolParams.fAllocateNetBuffer = TRUE;
    nblPoolParams.DataSize = 0;
    nblPoolParams.PoolTag = POOL_TAG;
    g_hNetBufferListPool = NdisAllocateNetBufferListPool(
        g_pNdisGenericObj,
        &nblPoolParams
        );
    if (NULL == g_hNetBufferListPool)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! NdisAllocateNetBufferListPool failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    nbPoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
    nbPoolParams.Header.Revision = NET_BUFFER_POOL_PARAMETERS_REVISION_1;
    nbPoolParams.Header.Size = NDIS_SIZEOF_NET_BUFFER_POOL_PARAMETERS_REVISION_1;
    nbPoolParams.DataSize = 0;
    nbPoolParams.PoolTag = POOL_TAG;
    g_hNetBufferPool = NdisAllocateNetBufferPool(
        g_pNdisGenericObj,
        &nbPoolParams
        );
    if (NULL == g_hNetBufferPool)
    {
        status = STATUS_NO_MEMORY;
        TraceEvents(
            TRACE_LEVEL_ERROR,
            TRACE_DRIVER,
            "%!FUNC! NdisAllocateNetBufferPool failed %!STATUS!",
            status
            );
        WPP_CLEANUP(DriverObject);
        return status;
    }
    status = dnsfilterCoInitialize(pDeviceObject);
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");
    return status;
}

NTSTATUS
dnsfilterDeviceAdd(
_In_    WDFDRIVER       Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit
)
/*++
Routine Description:

EvtDeviceAdd is called by the framework in response to AddDevice
call from the PnP manager. We create and initialize a device object to
represent a new instance of the device.

Arguments:

Driver - Handle to a framework driver object created in DriverEntry

DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.

Return Value:

NTSTATUS

--*/
{
    NTSTATUS status;
    UNREFERENCED_PARAMETER(Driver);
    PAGED_CODE();
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");
    status = dnsfilterCreateDevice(DeviceInit);
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");
    return status;
}

VOID
dnsfilterEvtDriverContextCleanup(
_In_ WDFOBJECT DriverObject
)
/*++
Routine Description:

Free all the resources allocated in DriverEntry.

Arguments:

DriverObject - handle to a WDF Driver object.

Return Value:

VOID.

--*/
{
    UNREFERENCED_PARAMETER(DriverObject);
    PAGED_CODE();
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");
    //
    // Stop WPP Tracing
    //
    WPP_CLEANUP(WdfDriverWdmGetDriverObject(DriverObject));
}

VOID dnsfilterEvtDriverUnload(
    __in  WDFDRIVER Driver
    )
{
    NTSTATUS    status;
    BOOLEAN bSignalWorkerThread;
    UNREFERENCED_PARAMETER(Driver);
    PAGED_CODE();
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");
    WdfObjectAcquireLock(g_wdfControlDevice);
    TraceEvents(
        TRACE_LEVEL_VERBOSE,
        TRACE_DRIVER,
        "%!FUNC! g_bDriverUnload = %!bool!",
        g_bDriverUnload
        );
    if (!g_bDriverUnload)
    {
        bSignalWorkerThread = IsListEmpty(&g_stPendedPacketsQueue);
        g_bDriverUnload = TRUE;
        if (bSignalWorkerThread)
        {
            KeSetEvent(
                &g_oWorkerEvent,
                0,
                FALSE
                );
        }
    }
    WdfObjectReleaseLock(g_wdfControlDevice);
    status = FwpsCalloutUnregisterById(
        g_nDatagramIdV6
        );
    status = FwpsCalloutUnregisterById(
        g_nDatagramId
        );
    status = FwpsCalloutUnregisterById(
        g_nStreamIdV6
        );
    status = FwpsCalloutUnregisterById(
        g_nStreamId
        );
    status = FwpsCalloutUnregisterById(
        g_nAleFlowEstablishedV6Id
        );
    status = FwpsCalloutUnregisterById(
        g_nAleFlowEstablishedId
        );
    status = FwpsInjectionHandleDestroy(
        g_hInjectionHandleV6
        );
    status = FwpsInjectionHandleDestroy(
        g_hInjectionHandle
        );
    if (NULL != g_hNetBufferPool)
    {
        NdisFreeNetBufferPool(g_hNetBufferPool);
        g_hNetBufferPool = NULL;
    }
    if (NULL != g_hNetBufferListPool)
    {
        NdisFreeNetBufferListPool(g_hNetBufferListPool);
        g_hNetBufferListPool = NULL;
    }
    if (NULL != g_pNdisGenericObj)
    {
        NdisFreeGenericObject(g_pNdisGenericObj);
        g_pNdisGenericObj = NULL;
    }
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");
}
